﻿using NServiceKit.Redis;
using System;
using System.Diagnostics;
using System.Text;
using Ninject;

namespace Demo
{
    using HobSoft.SoccerBet2014.Domain.IRepositories;
    using HobSoft.SoccerBet2014.Domain.DataService;
    using HobSoft.SoccerBet2014.Domain.Implementation.RedisRepository;
    using HobSoft.SoccerBet2014.Domain.Common.Site;
    using HobSoft.SoccerBet2014.Domain.Common.SiteContext;
    //1qaz3edc ibc
    //aaaa2222 sbo
    class Program
    {
        static void Main(string[] args)
        {
            Debug.Listeners.Add(new ConsoleTraceListener());
            string[] redisServer = new string[] { "localhost" };
            PooledRedisClientManager poolRedisManager = new PooledRedisClientManager(redisServer, redisServer, new RedisClientManagerConfig()
            {
                MaxReadPoolSize = 20,
                MaxWritePoolSize = 20,
                AutoStart = true
            });

            StoreCache2DB(poolRedisManager);

            //HobSoft.SoccerBet2014.Domain.Common.SiteContext.ContextManager.RedisPoolManager = poolRedisManager;
            //IGameRepository cacheGameRepository = new HobSoft.SoccerBet2014.Domain.Implementation.RedisRepository.GameRepository(poolRedisManager);
            //IMarketRepository cacheMarketRepository = new HobSoft.SoccerBet2014.Domain.Implementation.RedisRepository.MarketRepository(poolRedisManager);
            //IOddsRepository cacheOddsRepository = new HobSoft.SoccerBet2014.Domain.Implementation.RedisRepository.OddsRepository(poolRedisManager);
            //IBetGameDataService betGameService = new BetGameDataService(cacheGameRepository, cacheOddsRepository, cacheMarketRepository);

            //var cookiesManager = new StaticCookiesManager();
            //var cookiesManager = new RedisCookiesManager(poolRedisManager);
            //cookiesManager.Clear(11, "egqa0yg003");
            //cookiesManager.Clear(10, "SSYRA0YG003");
            //TestIbcSite(cookiesManager, betGameService);
            //TestSboSite(cookiesManager, betGameService);

            //Console.WriteLine(ibcSession.Md5EncryptPassword("1qaz2wsx", "4519"));
            Console.ReadLine();
        }

        static void StoreCache2DB(PooledRedisClientManager poolRedisManager)
        {
            //var dbContext = new HobSoft.SoccerBet2014.Domain.Models.DbContext.BetDbContext();
            //var bfDbContext = new HobSoft.SoccerBet2014.Domain.Models.DbContext.BFDbContext();

            //IGameRepository dbGameRepository = new HobSoft.SoccerBet2014.Domain.Implementation.SqlRepository.GameRepository(dbContext);
            //IGameRepository cacheGameRepository = new HobSoft.SoccerBet2014.Domain.Implementation.RedisRepository.GameRepository(poolRedisManager);
            //IBFEventRepository dbBfEventRepository = new HobSoft.SoccerBet2014.Domain.Implementation.SqlRepository.BFEventRepository(bfDbContext);
            //IBFEventRepository cacheBfEventRepository = new HobSoft.SoccerBet2014.Domain.Implementation.RedisRepository.BFEventRepository(poolRedisManager);
            //IGameMappingRepository dbMpRepository = new HobSoft.SoccerBet2014.Domain.Implementation.SqlRepository.GameMappingRepository(bfDbContext);
            //IGameMappingRepository cacheMpRepository = new HobSoft.SoccerBet2014.Domain.Implementation.RedisRepository.GameMappingRepository(poolRedisManager);
            //HobSoft.SoccerBet2014.Domain.Implementation.Service.PersistentModelsService pService =
            //    new HobSoft.SoccerBet2014.Domain.Implementation.Service.PersistentModelsService(
            //        dbGameRepository, cacheGameRepository, dbBfEventRepository, cacheBfEventRepository, dbMpRepository, cacheMpRepository);
            //pService.StoreEarlyGamesDb();

            using (var kernel=new Ninject.StandardKernel(new HobSoft.SoccerBet2014.Domain.Implementation.IocModule()))
            {
                var pService = kernel.Get<HobSoft.SoccerBet2014.Domain.Implementation.Service.PersistentModelsService>();
                pService.StoreBfEventCache();
            }

        }

        static void TestHgSite(HgSessionManager hgSession)
        {
            //var hgSession = new HgSessionManager(cookiesManager, sboRepository, "112.78.105.23", 12, "hob4mount");
            hgSession.Start().ContinueWith(t =>
            {
                if (t.Result)
                    hgSession.Signup("1qaz2wsx", "").ContinueWith(ts =>
                    {
                        if (ts.Result)
                        {
                            var result = hgSession.RequestMainPage();
                            Console.WriteLine(result.Result);
                        }
                    });
            });
        }

        static void TestSboSite(ICookiesManager cookiesManager, IBetGameDataService betGameService)
        {
            betGameService.DeleteExpiredGames(DateTime.Now.AddMinutes(150));
            var sboSession = new SboSessionManager(cookiesManager, betGameService, "sbo168.com", 11, "egqa0yg003");
            Stopwatch watch = new Stopwatch();
            watch.Start();

            if (!sboSession.ValidSessionOnline(DateTime.Now.AddMinutes(-5)))
            {
                sboSession.Start().ContinueWith(t =>
                {
                    watch.Stop();
                    Console.WriteLine("start: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
                    if (!t.Result)
                    {
                        Console.WriteLine("start error.");
                        return;
                    }
                    watch.Restart();
                    sboSession.Signup("aaaa1111").ContinueWith(ts =>
                    {
                        Console.WriteLine("signup: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
                        sboSession.RequestEarlyMarketOdds();
                        //UpdateSboAllOdds(sboSession);
                        // System.Threading.Thread.Sleep(10000);
                        //UpdateSboLiveOdds(sboSession);
                    });
                });
            }
            else
            {
                sboSession.RecoverContext();
                sboSession.RequestMainPage().ContinueWith(t =>
                {
                    UpdateSboAllOdds(sboSession);
                    System.Threading.Thread.Sleep(10000);
                    UpdateSboLiveOdds(sboSession);
                    UpdateSboTodayOdds(sboSession);
                });
            }
        }

        static void TestIbcSite(ICookiesManager cookiesManager, IBetGameDataService betGameService)
        {
            var ibcSession = new IbcSessionManager(cookiesManager, betGameService, "ibc123.com", 10, "SSYRA0YG003");
            betGameService.DeleteExpiredGames(DateTime.Now.AddMinutes(150));
            Stopwatch watch = new Stopwatch();
            watch.Start();
            if (!ibcSession.ValidSessionOnline(DateTime.Now.AddMinutes(-5)))
            {
                ibcSession.Start().ContinueWith(t =>
                {
                    watch.Stop();
                    Console.WriteLine("start: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
                    watch.Restart();
                    if (t.Result)
                        ibcSession.Signup("1qaz2wsx").ContinueWith(ts =>
                        {
                            watch.Stop();
                            Console.WriteLine("signup: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
                            ibcSession.RequestEarlyMarketOdds();
                            //UpdateIbcAllOdds(ibcSession);
                            //System.Threading.Thread.Sleep(10000);
                            //UpdateIbcLiveOdds(ibcSession);
                        });
                });

            }
            else
            {
                ibcSession.RecoverContext();
                UpdateIbcAllOdds(ibcSession);
                System.Threading.Thread.Sleep(10000);
                UpdateIbcLiveOdds(ibcSession);
            }

        }

        static void UpdateIbcAllOdds(IbcSessionManager ibcSession)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            ibcSession.RequestTodayMain().ContinueWith(t =>
            {
                var result2 = ibcSession.RequestLiveFullOdds();
                if (!result2.IsCanceled && result2.Exception == null)
                {
                    if (result2.Result != null)
                        Console.WriteLine("live update count : {0}", result2.Result.Count);
                    watch.Stop();
                    Console.WriteLine("reques live odds: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
                }
                else
                {
                    Console.WriteLine(result2.Exception.InnerException.Message);
                }
                watch.Restart();
                var result1 = ibcSession.RequestTodayFullOdds();
                if (!result1.IsCanceled && result2.Exception == null)
                {
                    if (result1.Result != null)
                        Console.WriteLine("today update count : {0}", result1.Result.Count);
                    watch.Stop();
                    Console.WriteLine("reques today odds: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
                }
                else
                {
                    Console.WriteLine(result1.Exception.InnerException.Message);
                }
            });
        }

        static void UpdateSboAllOdds(SboSessionManager sboSession)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            var result2 = sboSession.RequestLiveFullOdds();
            if (!result2.IsCanceled && result2.Exception == null)
            {
                if (result2.Result != null)
                    Console.WriteLine("live update count : {0}", result2.Result.Count);
                watch.Stop();
                Console.WriteLine("reques live odds: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
            }
            else
            {
                Console.WriteLine(result2.Exception.InnerException.Message);
            }
            watch.Restart();
            var result1 = sboSession.RequestTodayFullOdds();
            if (!result1.IsCanceled && result2.Exception == null)
            {
                if (result1.Result != null)
                    Console.WriteLine("live update count : {0}", result1.Result.Count);
                watch.Stop();
                Console.WriteLine("reques today odds: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
            }
            else
            {
                Console.WriteLine(result1.Exception.InnerException.Message);
            }
        }

        static void UpdateIbcLiveOdds(IbcSessionManager ibcSession)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            ibcSession.RequestUpdateLiveOdds().ContinueWith(t =>
            {
                Console.WriteLine(t.Result);
                watch.Stop();
                Console.WriteLine("reques update live odds: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
                System.Threading.Thread.Sleep(10000);
                UpdateIbcLiveOdds(ibcSession);
            });
        }

        static void UpdateIbcTodayOdds(IbcSessionManager ibcSession)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            ibcSession.RequestUpdateTodayOdds().ContinueWith(t =>
            {
                Console.WriteLine(t.Result);
                watch.Stop();
                Console.WriteLine("reques update today odds: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
                System.Threading.Thread.Sleep(10000);
                UpdateIbcTodayOdds(ibcSession);
            });
        }

        static void UpdateSboLiveOdds(SboSessionManager sboSession)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            sboSession.RequestLiveOdds(false).ContinueWith(t =>
            {
                if (t.Exception != null || t.IsCanceled) return;
                Console.WriteLine(t.Result);
                watch.Stop();
                Console.WriteLine("reques update live odds: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
                System.Threading.Thread.Sleep(10000);
                UpdateSboLiveOdds(sboSession);
            });
        }

        static void UpdateSboTodayOdds(SboSessionManager sboSession)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            sboSession.RequestTodayOdds(false).ContinueWith(t =>
            {
                Console.WriteLine(t.Result);
                watch.Stop();
                Console.WriteLine("reques update today odds: {0:f3}", (double)watch.ElapsedMilliseconds / (double)1000);
                System.Threading.Thread.Sleep(100000);
                UpdateSboTodayOdds(sboSession);
            });
        }


        public static String bytesToHexString(byte[] bArray)
        {
            StringBuilder sb = new StringBuilder(bArray.Length);
            String sTemp;
            for (int i = 0; i < bArray.Length; i++)
            {
                sTemp = bArray[i].ToString("X");
                if (sTemp.Length < 2)
                    sb.Append(0);
                sb.Append(sTemp.ToUpper());
            }
            return sb.ToString();
        }

        static string CFS(string str)
        {
            var c = (char)21;
            var len = 30;
            var padStr = str.PadRight(len, c);
            double num = 1;
            for (int i = 0; i < len; i++)
            {
                int val = len + (i + 1) * (int)padStr[i];
                num = num * val;
            }
            var numStr = num.ToString("E14").ToUpper();
            var resetNumStr = numStr.Replace("E+0", "E+");
            Console.WriteLine(resetNumStr);
            var m = "";
            for (var i = 0; i < resetNumStr.Length; i++)
            {
                string int4Val = "";
                if (i == resetNumStr.Length - 1)
                {
                    int4Val = ((int)resetNumStr[i]).ToString();
                    Console.WriteLine(string.Format("{0}", resetNumStr[i]));
                }
                else if (i == resetNumStr.Length - 2)
                {
                    int4Val = string.Format("{0}{1}", (int)resetNumStr[i], (int)resetNumStr[i + 1]);
                    Console.WriteLine(string.Format("{0}{1}", resetNumStr[i], resetNumStr[i + 1]));
                }
                else
                {
                    int4Val = string.Format("{0}{1}{2}", (int)resetNumStr[i], (int)resetNumStr[i + 1], (int)resetNumStr[i + 2]);
                    Console.WriteLine(string.Format("{0}{1}{2}", resetNumStr[i], resetNumStr[i + 1], resetNumStr[i + 2]));
                }
                //   Console.WriteLine(int4Val);
                m = m + Convert.ToInt32(int4Val).ToString("x");
            }
            var result = "";
            for (var b = 20; b <= m.Length - 18; b += 2)
            {
                result = result + m[b - 1];
            }

            Console.WriteLine(m);
            Console.WriteLine(result);
            return result.ToUpper();
        }
    }
}
